
import React from "react";
import defaultIcon from "./defaultIcon";
import classnames from "classnames";
import styles from './index.module.less';

const cache: any = {}

// 加载图标的根路径
const ICON_PATH = import.meta.env.BASE_URL + "menu-icons";
export interface IIconProps {
    id?: string | null
}

export function Icon(props: IIconProps) {

    const { id } = props;

    const [iconStr, setIconStr] = React.useState<string>("");

    // 加载图标
    React.useEffect(() => {
        const url = `${ICON_PATH}/${id}.svg`;
        if (cache[url]) {
            setIconStr(cache[url]);
        } else {
            fetch(url)
                .then(res => res.text())
                .then(text => {
                    if (text.includes('<svg')) {
                        setIconStr(text);
                        cache[url] = text;
                    } else {
                        setIconStr(defaultIcon);
                        cache[url] = defaultIcon;
                    }
                }).catch(() => {
                    setIconStr(defaultIcon);
                    cache[url] = defaultIcon;
                })
        }
    }, [id])

    // 渲染图标
    return <i className={classnames(['anticon', styles.icon])} dangerouslySetInnerHTML={{ __html: iconStr }} />
}